Page({
  data: {
    loading: true,
    loadingMore: false,
    logs: [],
    stats: null,
    currentPage: 1,
    pageSize: 20,
    hasMore: false,
    expandedLogs: {}, // 展开的日志详情
    
    // 筛选选项
    loginTypeOptions: [
      { key: '', name: '全部类型' },
      { key: 'wechat', name: '微信登录' },
      { key: 'anonymous', name: '匿名登录' },
      { key: 'phone', name: '手机登录' },
      { key: 'email', name: '邮箱登录' }
    ],
    loginTypeIndex: 0,
    selectedLoginType: ''
  },

  async onLoad() {
    wx.setNavigationBarTitle({
      title: '登录日志管理 (管理员)'
    })

    // 检查管理员权限
    await this.checkAdminPermission()
  },

  // 检查管理员权限
  async checkAdminPermission() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'checkUserPermission',
        data: { permission: 'basic' }
      })

      if (result.result && result.result.success) {
        const data = result.result.data
        const userPermissions = data.permissions || ['basic']
        const userRole = data.role || 'user'

        // 检查是否有管理员权限
        const hasAdminPermission = userPermissions.includes('admin') ||
                                 userPermissions.includes('super_admin') ||
                                 userRole === 'admin' ||
                                 userRole === 'super_admin'

        if (hasAdminPermission) {
          console.log('✅ 管理员权限验证通过，加载登录日志')
          this.loadLoginLogs(true)
        } else {
          console.log('❌ 权限不足，无法访问登录日志')
          this.showNoPermission()
        }
      } else {
        throw new Error('权限检查失败')
      }
    } catch (error) {
      console.error('❌ 权限检查异常:', error)
      this.showNoPermission()
    }
  },

  // 显示无权限页面
  showNoPermission() {
    wx.showModal({
      title: '权限不足',
      content: '您没有管理员权限，无法查看登录日志。',
      showCancel: false,
      confirmText: '返回',
      success: () => {
        wx.navigateBack()
      }
    })
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadLoginLogs(true)
  },

  // 加载登录日志
  async loadLoginLogs(reset = false) {
    if (reset) {
      this.setData({
        loading: true,
        logs: [],
        currentPage: 1,
        hasMore: false,
        expandedLogs: {}
      })
    }

    try {
      console.log('📊 开始加载登录日志...')

      const result = await wx.cloud.callFunction({
        name: 'getUserLoginLogs',
        data: {
          page: reset ? 1 : this.data.currentPage,
          pageSize: this.data.pageSize,
          loginType: this.data.selectedLoginType || null
        }
      })

      console.log('📊 登录日志云函数调用结果:', result)

      if (result.result && result.result.success) {
        const { logs, pagination, stats } = result.result.data

        console.log('📊 获取到的日志数据:', { logs, pagination, stats })

        this.setData({
          logs: reset ? logs : [...this.data.logs, ...logs],
          currentPage: pagination.page,
          hasMore: pagination.hasMore,
          stats: stats
        })

        console.log(`✅ 加载了 ${logs.length} 条登录日志，总计 ${pagination.totalCount} 条`)

        if (logs.length === 0 && reset) {
          wx.showToast({
            title: '暂无登录记录',
            icon: 'none'
          })
        }
      } else {
        console.error('❌ 云函数返回错误:', result.result)
        throw new Error(result.result?.error || '加载失败')
      }

    } catch (error) {
      console.error('❌ 加载登录日志失败:', error)
      console.error('❌ 错误详情:', error.message)

      wx.showModal({
        title: '加载失败',
        content: `无法加载登录日志：${error.message}\n\n请确保云函数已正确部署`,
        showCancel: true,
        cancelText: '返回',
        confirmText: '重试',
        success: (res) => {
          if (res.confirm) {
            this.loadLoginLogs(true)
          } else if (res.cancel) {
            wx.navigateBack()
          }
        }
      })
    } finally {
      this.setData({
        loading: false,
        loadingMore: false
      })
    }
  },

  // 加载更多日志
  async loadMoreLogs() {
    if (this.data.loadingMore || !this.data.hasMore) return

    this.setData({ 
      loadingMore: true,
      currentPage: this.data.currentPage + 1
    })

    await this.loadLoginLogs(false)
  },

  // 切换登录类型筛选
  onLoginTypeChange(e) {
    const index = e.detail.value
    const selectedType = this.data.loginTypeOptions[index]
    
    console.log('🔍 切换登录类型筛选:', selectedType.name)
    
    this.setData({
      loginTypeIndex: index,
      selectedLoginType: selectedType.key
    })
    
    // 重新加载数据
    this.loadLoginLogs(true)
  },

  // 刷新日志
  refreshLogs() {
    console.log('🔄 刷新登录日志')
    this.loadLoginLogs(true)
  },

  // 切换日志详情展开状态
  toggleLogDetail(e) {
    const logId = e.currentTarget.dataset.id
    const expandedLogs = { ...this.data.expandedLogs }
    
    expandedLogs[logId] = !expandedLogs[logId]
    
    this.setData({ expandedLogs })
    
    console.log('📋 切换日志详情:', logId, expandedLogs[logId] ? '展开' : '收起')
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadLoginLogs(true).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 分享页面
  onShareAppMessage() {
    return {
      title: '登录日志管理',
      path: '/pages/login-logs/login-logs'
    }
  }
})
